package com.ahdy.tool;

import com.ahdy.entity.Medication;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 药品数据清洗工具类
 * 用于从OCR识别的文字中提取药品信息
 *
 * @author ahdy
 * @version 1.0
 */
@Slf4j
@Component
public class MedicationDataCleaner {

    // ==================== 关键词定义 ====================

    /** 药品名称相关关键词 */
    private static final String[] NAME_KEYWORDS = {
            "通用名", "药品名称", "商品名", "品名", "药名", "名称"
    };

    /** 生产厂家相关关键词 */
    private static final String[] MANUFACTURER_KEYWORDS = {
            "生产企业", "制造商", "生产厂家", "厂家", "企业", "公司", "制药"
    };

    /** 处方药关键词 */
    private static final String[] PRESCRIPTION_KEYWORDS = {
            "处方药", "Rx", "凭处方", "医师处方"
    };

    /** 非处方药关键词 */
    private static final String[] OTC_KEYWORDS = {
            "非处方药", "OTC", "甲类", "乙类"
    };

    /** 副作用相关关键词 */
    private static final String[] SIDE_EFFECTS_KEYWORDS = {
            "不良反应", "副作用", "禁忌", "注意事项", "慎用"
    };

    /** 说明书相关关键词 */
    private static final String[] DESCRIPTION_KEYWORDS = {
            "适应症", "功能主治", "用法用量", "性状", "成分"
    };

    /** 用法用量相关关键词 */
    private static final String[] DOSAGE_KEYWORDS = {
            "用法用量", "用法", "用量", "服用方法", "服用剂量", "每次", "单次"
    };

    /** 服用频次相关关键词 */
    private static final String[] FREQUENCY_KEYWORDS = {
            "每日", "每天", "一日", "一天", "次/日", "次/天", "日服", "天服"
    };

    /** 特殊说明相关关键词 */
    private static final String[] SPECIAL_INSTRUCTIONS_KEYWORDS = {
            "特殊说明", "注意事项", "警告", "重要提示", "特别提醒", "服药提醒", "饭前", "饭后", "空腹", "餐时"
    };

    // ==================== 主要方法 ====================

    /**
     * 从OCR识别文字中提取药品信息
     *
     * @param ocrText OCR识别的文字
     * @return 包含药品信息和额外字段的Map
     */
    public Map<String, Object> extractMedicationInfo(String ocrText) {
        if (ocrText == null || ocrText.trim().isEmpty()) {
            log.warn("OCR文字为空，无法提取药品信息");
            return null;
        }

        log.info("开始提取药品信息，OCR文字长度: {}", ocrText.length());

        // 清理文本
        String cleanText = cleanText(ocrText);

        // 创建药品实体
        Medication medication = new Medication();

        // 提取基本信息
        extractBasicInfo(medication, cleanText);

        // 提取额外字段
        String singleDosage = extractSingleDosage(cleanText);
        Integer dailyFrequency = extractDailyFrequency(cleanText);
        String specialInstructions = extractSpecialInstructions(cleanText);

        // 验证提取的信息
        validateMedicationName(medication);

        log.info("药品信息提取完成: 名称={}, 厂家={}, 类型={}, 单次剂量={}, 每日次数={}",
                medication.getName(), medication.getManufacturer(), medication.getType(),
                singleDosage, dailyFrequency);

        // 返回包含所有信息的Map
        return createResultMap(medication, singleDosage, dailyFrequency, specialInstructions);
    }

    /**
     * 验证提取的药品信息是否有效
     */
    public boolean isValidMedication(Medication medication) {
        if (medication == null) {
            return false;
        }

        // 至少需要有药品名称
        if (medication.getName() == null || medication.getName().trim().isEmpty()) {
            log.warn("药品信息无效：缺少药品名称");
            return false;
        }

        // 药品名称不能太短或太长
        String name = medication.getName().trim();
        if (name.length() < 2 || name.length() > 100) {
            log.warn("药品信息无效：药品名称长度不合适 ({})", name.length());
            return false;
        }

        log.debug("药品信息验证通过");
        return true;
    }

    /**
     * 验证提取的完整药品信息是否有效（包含额外字段）
     */
    public boolean isValidMedicationInfo(Map<String, Object> medicationInfo) {
        if (medicationInfo == null) {
            log.warn("药品信息Map为空");
            return false;
        }

        Medication medication = (Medication) medicationInfo.get("medication");
        if (!isValidMedication(medication)) {
            return false;
        }

        // 检查额外字段的有效性
        String singleDosage = (String) medicationInfo.get("singleDosage");
        Integer dailyFrequency = (Integer) medicationInfo.get("dailyFrequency");

        // 如果提取到了剂量信息，进行简单验证
        if (singleDosage != null && singleDosage.trim().length() > 50) {
            log.warn("单次剂量信息过长: {}", singleDosage.length());
        }

        // 如果提取到了频次信息，进行合理性验证
        if (dailyFrequency != null && (dailyFrequency < 1 || dailyFrequency > 10)) {
            log.warn("每日服用次数可能不合理: {}", dailyFrequency);
        }

        log.debug("完整药品信息验证通过");
        return true;
    }

    /**
     * 创建包含所有信息的完整药品数据对象
     */
    public Map<String, Object> createCompleteMedicationData(Map<String, Object> extractedInfo) {
        if (extractedInfo == null) {
            return null;
        }

        Map<String, Object> completeData = new HashMap<>();

        // 基本药品信息
        Medication medication = (Medication) extractedInfo.get("medication");
        completeData.put("medication", medication);

        // 额外字段
        completeData.put("singleDosage", extractedInfo.get("singleDosage"));
        completeData.put("dailyFrequency", extractedInfo.get("dailyFrequency"));
        completeData.put("specialInstructions", extractedInfo.get("specialInstructions"));

        // 添加提取状态信息
        Map<String, Object> extractionStatus = new HashMap<>();
        extractionStatus.put("hasName", medication != null && medication.getName() != null);
        extractionStatus.put("hasManufacturer", medication != null && medication.getManufacturer() != null);
        extractionStatus.put("hasDosage", extractedInfo.get("singleDosage") != null);
        extractionStatus.put("hasFrequency", extractedInfo.get("dailyFrequency") != null);
        extractionStatus.put("hasInstructions", extractedInfo.get("specialInstructions") != null);
        completeData.put("extractionStatus", extractionStatus);

        return completeData;
    }

    // ==================== 私有辅助方法 ====================

    /**
     * 清理文本，去除多余的空格和特殊字符
     */
    private String cleanText(String text) {
        if (text == null) return "";

        return text
                .replaceAll("\\s+", " ")  // 多个空格替换为单个空格
                .replaceAll("[\\r\\n]+", "\n")  // 多个换行符替换为单个换行符
                .trim();
    }

    /**
     * 提取基本药品信息
     */
    private void extractBasicInfo(Medication medication, String cleanText) {
        // 提取药品名称
        String name = extractName(cleanText);
        if (name != null && !name.trim().isEmpty()) {
            medication.setName(name.trim());
        }

        // 提取生产厂家
        String manufacturer = extractManufacturer(cleanText);
        if (manufacturer != null && !manufacturer.trim().isEmpty()) {
            medication.setManufacturer(manufacturer.trim());
        }

        // 提取药品类型
        Medication.MedicationType type = extractMedicationType(cleanText);
        medication.setType(type);

        // 提取描述信息
        String description = extractDescription(cleanText);
        if (description != null && !description.trim().isEmpty()) {
            medication.setDescription(description.trim());
        }

        // 提取副作用信息
        String sideEffects = extractSideEffects(cleanText);
        if (sideEffects != null && !sideEffects.trim().isEmpty()) {
            medication.setSideEffects(sideEffects.trim());
        }
    }

    /**
     * 验证药品名称
     */
    private void validateMedicationName(Medication medication) {
        if (medication.getName() == null || medication.getName().trim().isEmpty()) {
            log.warn("未能提取到药品名称，使用默认值");
            medication.setName("未识别药品名称");
        }
    }

    /**
     * 创建结果Map
     */
    private Map<String, Object> createResultMap(Medication medication, String singleDosage,
                                                Integer dailyFrequency, String specialInstructions) {
        Map<String, Object> result = new HashMap<>();
        result.put("medication", medication);
        result.put("singleDosage", singleDosage);
        result.put("dailyFrequency", dailyFrequency);
        result.put("specialInstructions", specialInstructions);
        return result;
    }

    /**
     * 提取药品名称
     */
    private String extractName(String text) {
        // 针对实际OCR文本格式，优化药品名称提取

        // 方法1：匹配"通用名称：药品名"格式
        Pattern namePattern1 = Pattern.compile("通用名称[：:：\\s]*([\\u4e00-\\u9fa5a-zA-Z0-9]+)", Pattern.CASE_INSENSITIVE);
        Matcher matcher1 = namePattern1.matcher(text);
        if (matcher1.find()) {
            String name = matcher1.group(1).trim();
            if (name.length() >= 2 && name.length() <= 50) {
                log.debug("通过'通用名称'提取到药品名称: {}", name);
                return name;
            }
        }

        // 方法2：匹配"药品名称：药品名"格式
        Pattern namePattern2 = Pattern.compile("药品名称[：:：\\s]*([\\u4e00-\\u9fa5a-zA-Z0-9]+)", Pattern.CASE_INSENSITIVE);
        Matcher matcher2 = namePattern2.matcher(text);
        if (matcher2.find()) {
            String name = matcher2.group(1).trim();
            if (name.length() >= 2 && name.length() <= 50) {
                log.debug("通过'药品名称'提取到药品名称: {}", name);
                return name;
            }
        }

        // 方法3：匹配说明书标题格式，如"小柴胡颗粒说明书"
        Pattern titlePattern = Pattern.compile("([\\u4e00-\\u9fa5a-zA-Z0-9]{2,20})[颗粒片胶囊丸剂膏贴]说明书", Pattern.CASE_INSENSITIVE);
        Matcher titleMatcher = titlePattern.matcher(text);
        if (titleMatcher.find()) {
            String name = titleMatcher.group(1) + titleMatcher.group(0).replaceAll("说明书", "").substring(titleMatcher.group(1).length());
            if (name.length() >= 2 && name.length() <= 50) {
                log.debug("通过说明书标题提取到药品名称: {}", name);
                return name;
            }
        }

        // 方法4：其他关键词匹配（保持原有逻辑但更严格）
        for (String keyword : NAME_KEYWORDS) {
            if (keyword.equals("通用名") || keyword.equals("药品名称")) continue; // 已在上面处理

            Pattern pattern = Pattern.compile(keyword + "[：:：\\s]*([\\u4e00-\\u9fa5a-zA-Z0-9]{2,30})", Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(text);
            if (matcher.find()) {
                String name = matcher.group(1).trim();
                // 去掉可能的后缀
                name = name.replaceAll("\\s*(汉语拼音|拼音|英文名).*", "").trim();
                if (name.length() >= 2 && name.length() <= 50) {
                    log.debug("通过关键词 '{}' 提取到药品名称: {}", keyword, name);
                    return name;
                }
            }
        }

        // 方法5：从文本开头几行寻找可能的药品名称
        String[] lines = text.split("\\n");
        for (int i = 0; i < Math.min(lines.length, 10); i++) {
            String line = lines[i].trim();
            // 跳过公司名、OTC等标识
            if (line.contains("公司") || line.contains("企业") || line.contains("OTC") ||
                    line.contains("甲类") || line.contains("乙类") || line.length() < 3) {
                continue;
            }

            // 查找可能的药品名称
            if (line.matches(".*[\\u4e00-\\u9fa5]+[颗粒片胶囊丸剂膏贴].*") && line.length() <= 30) {
                String cleanName = line.replaceAll("说明书|请仔细阅读.*", "").trim();
                if (cleanName.length() >= 3 && cleanName.length() <= 20) {
                    log.debug("从文本行提取到可能的药品名称: {}", cleanName);
                    return cleanName;
                }
            }
        }

        log.debug("未能提取到药品名称");
        return null;
    }

    /**
     * 提取生产厂家
     */
    private String extractManufacturer(String text) {
        for (String keyword : MANUFACTURER_KEYWORDS) {
            Pattern pattern = Pattern.compile(keyword + "[：:：\\s]*([\\u4e00-\\u9fa5a-zA-Z0-9\\s\\(\\)（）]+)", Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(text);
            if (matcher.find()) {
                String manufacturer = matcher.group(1).trim();
                // 去掉可能的尾部信息
                manufacturer = manufacturer.split("[，,。.]")[0].trim();
                // 去掉"生产地址"、"注册地址"等后缀
                manufacturer = manufacturer.replaceAll("\\s*(生产地址|注册地址|地址|电话|邮编|邮政编码).*", "").trim();
                // 去掉换行后的内容
                manufacturer = manufacturer.split("\\n")[0].trim();
                if (manufacturer.length() > 0 && manufacturer.length() <= 100) {
                    log.debug("通过关键词 '{}' 提取到生产厂家: {}", keyword, manufacturer);
                    return manufacturer;
                }
            }
        }

        // 尝试查找包含"公司"、"企业"、"制药"的行
        String[] lines = text.split("\\n");
        for (String line : lines) {
            line = line.trim();
            if ((line.contains("公司") || line.contains("企业") || line.contains("制药")) &&
                    line.length() <= 100 && line.length() > 3 &&
                    !line.contains("电话") && !line.contains("地址") && !line.contains("邮编")) {
                // 清理可能的前缀
                String cleanManufacturer = line.replaceAll("^.*?([\\u4e00-\\u9fa5]+.*?(?:公司|企业|制药)).*", "$1").trim();
                if (cleanManufacturer.length() > 3) {
                    log.debug("从文本中提取到可能的生产厂家: {}", cleanManufacturer);
                    return cleanManufacturer;
                }
            }
        }

        log.debug("未能提取到生产厂家信息");
        return null;
    }

    /**
     * 提取药品类型
     */
    private Medication.MedicationType extractMedicationType(String text) {
        String upperText = text.toUpperCase();

        // 检查是否为处方药
        for (String keyword : PRESCRIPTION_KEYWORDS) {
            if (upperText.contains(keyword.toUpperCase())) {
                log.debug("检测到处方药关键词: {}", keyword);
                return Medication.MedicationType.处方药;
            }
        }

        // 检查是否为非处方药
        for (String keyword : OTC_KEYWORDS) {
            if (upperText.contains(keyword.toUpperCase())) {
                log.debug("检测到非处方药关键词: {}", keyword);
                return Medication.MedicationType.非处方药;
            }
        }

        // 默认为处方药
        log.debug("未能确定药品类型，默认设置为处方药");
        return Medication.MedicationType.处方药;
    }

    /**
     * 提取描述信息
     */
    private String extractDescription(String text) {
        StringBuilder description = new StringBuilder();

        // 按优先级提取各种描述信息
        String[] descriptionSections = {
                "功能主治", "适应症", "用法用量", "规格", "性状", "成分"
        };

        for (String section : descriptionSections) {
            // 匹配方括号格式：[功能主治]内容
            Pattern pattern = Pattern.compile("\\[" + section + "\\]([^\\[]*?)(?=\\[|$)", Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(text);
            if (matcher.find()) {
                String content = matcher.group(1).trim();
                // 清理内容
                content = cleanDescriptionContent(content);
                if (content.length() > 5 && content.length() <= 300) {
                    if (description.length() > 0) {
                        description.append("；");
                    }
                    description.append(section).append("：").append(content);

                    // 如果已经有足够的描述信息，就停止
                    if (description.length() > 200) {
                        break;
                    }
                }
            }
        }

        String result = description.toString();
        if (result.length() > 500) {
            result = result.substring(0, 500) + "...";
        }

        if (!result.isEmpty()) {
            log.debug("提取到描述信息，长度: {}", result.length());
            return result;
        }

        log.debug("未能提取到描述信息");
        return null;
    }

    /**
     * 提取副作用信息
     */
    private String extractSideEffects(String text) {
        StringBuilder sideEffects = new StringBuilder();

        // 按优先级提取副作用相关信息
        String[] sideEffectSections = {
                "不良反应", "禁忌", "注意事项"
        };

        for (String section : sideEffectSections) {
            // 匹配方括号格式：[不良反应]内容
            Pattern pattern = Pattern.compile("\\[" + section + "\\]([^\\[]*?)(?=\\[|$)", Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(text);
            if (matcher.find()) {
                String content = matcher.group(1).trim();
                // 清理内容
                content = cleanSideEffectContent(content);
                if (content.length() > 5 && content.length() <= 200) {
                    if (sideEffects.length() > 0) {
                        sideEffects.append("；");
                    }
                    sideEffects.append(section).append("：").append(content);

                    // 如果已经有足够的副作用信息，就停止
                    if (sideEffects.length() > 300) {
                        break;
                    }
                }
            }
        }

        String result = sideEffects.toString();
        if (result.length() > 500) {
            result = result.substring(0, 500) + "...";
        }

        if (!result.isEmpty()) {
            log.debug("提取到副作用信息，长度: {}", result.length());
            return result;
        }

        log.debug("未能提取到副作用信息");
        return null;
    }

    /**
     * 清理描述内容
     */
    private String cleanDescriptionContent(String content) {
        if (content == null) return "";

        return content
                .replaceAll("\\]", "") // 去掉右方括号
                .replaceAll("\\n+", " ") // 换行替换为空格
                .replaceAll("\\s+", " ") // 多个空格替换为单个
                .replaceAll("^[\\s\\]]+", "") // 去掉开头的空格和方括号
                .trim();
    }

    /**
     * 清理副作用内容
     */
    private String cleanSideEffectContent(String content) {
        if (content == null) return "";

        // 对于注意事项，只保留前几条重要的
        if (content.contains("1.") && content.length() > 100) {
            // 提取前3条注意事项
            String[] items = content.split("\\d+\\.");
            StringBuilder shortContent = new StringBuilder();
            for (int i = 1; i <= Math.min(items.length - 1, 3); i++) {
                if (items[i].trim().length() > 5) {
                    if (shortContent.length() > 0) {
                        shortContent.append("；");
                    }
                    shortContent.append(items[i].trim());
                }
            }
            content = shortContent.toString();
        }

        return content
                .replaceAll("\\]", "") // 去掉右方括号
                .replaceAll("\\n+", " ") // 换行替换为空格
                .replaceAll("\\s+", " ") // 多个空格替换为单个
                .replaceAll("^[\\s\\]]+", "") // 去掉开头的空格和方括号
                .replaceAll("监测数据显示，本品可见以下不良反应", "") // 去掉固定前缀
                .trim();
    }

    /**
     * 提取单次剂量信息
     */
    private String extractSingleDosage(String text) {
        // 匹配常见的剂量表达模式，包括范围表达
        String[] dosagePatterns = {
                // 支持范围表达：1-2袋、1～2袋、1一2袋
                "每次[服用]?([0-9]+[\\-～一][0-9]+[毫克mgMG片粒颗粒袋包支丸])",
                "单次[服用]?([0-9]+[\\-～一][0-9]+[毫克mgMG片粒颗粒袋包支丸])",
                "一次([0-9]+[\\-～一][0-9]+[毫克mgMG片粒颗粒袋包支丸])",

                // 单一剂量
                "每次[服用]?([0-9]+(?:\\.[0-9]+)?[毫克mgMG片粒颗粒袋包支丸])",
                "单次[服用]?([0-9]+(?:\\.[0-9]+)?[毫克mgMG片粒颗粒袋包支丸])",
                "一次([0-9]+(?:\\.[0-9]+)?[毫克mgMG片粒颗粒袋包支丸])",
                "([0-9]+(?:\\.[0-9]+)?[毫克mgMG片粒颗粒袋包支丸])/次",
                "([0-9]+(?:\\.[0-9]+)?[毫克mgMG片粒颗粒袋包支丸])每次",

                // 更多匹配模式
                "成人.*?每次([0-9]+[\\-～一]?[0-9]*[毫克mgMG片粒颗粒袋包支丸])",
                "口服.*?每次([0-9]+[\\-～一]?[0-9]*[毫克mgMG片粒颗粒袋包支丸])",
                "服用.*?每次([0-9]+[\\-～一]?[0-9]*[毫克mgMG片粒颗粒袋包支丸])",

                // 匹配简单形式：1袋、2片等
                "每次([0-9]+[\\-～一]?[0-9]*[袋包片粒支丸颗粒])",
                "一次([0-9]+[\\-～一]?[0-9]*[袋包片粒支丸颗粒])",
                "单次([0-9]+[\\-～一]?[0-9]*[袋包片粒支丸颗粒])"
        };

        // 首先在整个文本中搜索
        for (String pattern : dosagePatterns) {
            Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
            Matcher matcher = p.matcher(text);
            if (matcher.find()) {
                String dosage = matcher.group(1);
                log.debug("提取到单次剂量: {}", dosage);
                return dosage;
            }
        }

        // 从用法用量段落中提取
        String[] usageKeywords = {"用法用量", "用法", "用量", "服用方法", "服用剂量"};
        for (String keyword : usageKeywords) {
            Pattern sectionPattern = Pattern.compile("\\[" + keyword + "\\]([^\\[]*)", Pattern.CASE_INSENSITIVE);
            Matcher sectionMatcher = sectionPattern.matcher(text);
            if (sectionMatcher.find()) {
                String usageSection = sectionMatcher.group(1);
                log.debug("找到用法用量段落: {}", usageSection);

                // 在用法用量段落中查找剂量
                for (String dosagePattern : dosagePatterns) {
                    Pattern p = Pattern.compile(dosagePattern, Pattern.CASE_INSENSITIVE);
                    Matcher dosageMatcher = p.matcher(usageSection);
                    if (dosageMatcher.find()) {
                        String dosage = dosageMatcher.group(1);
                        log.debug("从用法用量段落提取到单次剂量: {}", dosage);
                        return dosage;
                    }
                }
            }
        }

        // 尝试查找"成人用量"、"成人剂量"等相关信息
        String[] adultDosagePatterns = {
                "成人.*?([0-9]+[\\-～一]?[0-9]*(?:\\.[0-9]+)?[毫克mgMG片粒颗粒袋包支丸])",
                "成人.*?每次.*?([0-9]+[\\-～一]?[0-9]*[袋包片粒支丸颗粒])",
                "口服.*?([0-9]+[\\-～一]?[0-9]*(?:\\.[0-9]+)?[毫克mgMG片粒颗粒袋包支丸])"
        };

        for (String pattern : adultDosagePatterns) {
            Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
            Matcher matcher = p.matcher(text);
            if (matcher.find()) {
                String dosage = matcher.group(1);
                log.debug("从成人用量信息提取到单次剂量: {}", dosage);
                return dosage;
            }
        }

        log.debug("未能提取到单次剂量信息");
        return null;
    }

    /**
     * 提取每日服用次数
     */
    private Integer extractDailyFrequency(String text) {
        // 匹配常见的频次表达模式
        String[] frequencyPatterns = {
                "每日([0-9]+)次",
                "每天([0-9]+)次",
                "一日([0-9]+)次",
                "一天([0-9]+)次",
                "([0-9]+)次/日",
                "([0-9]+)次/天",
                "日服([0-9]+)次",
                "天服([0-9]+)次",
                "([0-9]+)次每日",
                "([0-9]+)次每天"
        };

        for (String pattern : frequencyPatterns) {
            Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
            Matcher matcher = p.matcher(text);
            if (matcher.find()) {
                try {
                    int frequency = Integer.parseInt(matcher.group(1));
                    log.debug("提取到每日服用次数: {}", frequency);
                    return frequency;
                } catch (NumberFormatException e) {
                    log.warn("解析服用次数失败: {}", matcher.group(1));
                }
            }
        }

        // 尝试从用法用量段落中提取
        for (String keyword : DOSAGE_KEYWORDS) {
            Pattern pattern = Pattern.compile(keyword + "[：:：\\s]*([^\\n]*)", Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(text);
            if (matcher.find()) {
                String dosageSection = matcher.group(1);
                // 在这个段落中再次查找频次模式
                for (String frequencyPattern : frequencyPatterns) {
                    Pattern p = Pattern.compile(frequencyPattern, Pattern.CASE_INSENSITIVE);
                    Matcher frequencyMatcher = p.matcher(dosageSection);
                    if (frequencyMatcher.find()) {
                        try {
                            int frequency = Integer.parseInt(frequencyMatcher.group(1));
                            log.debug("从用法用量段落提取到每日服用次数: {}", frequency);
                            return frequency;
                        } catch (NumberFormatException e) {
                            log.warn("解析服用次数失败: {}", frequencyMatcher.group(1));
                        }
                    }
                }
            }
        }

        log.debug("未能提取到每日服用次数");
        return null;
    }

    /**
     * 提取特殊说明信息
     */
    private String extractSpecialInstructions(String text) {
        StringBuilder instructions = new StringBuilder();

        // 从注意事项中提取重要信息
        Pattern noticePattern = Pattern.compile("\\[注意事项\\]([^\\[]*?)(?=\\[|$)", Pattern.CASE_INSENSITIVE);
        Matcher noticeMatcher = noticePattern.matcher(text);
        if (noticeMatcher.find()) {
            String noticeContent = noticeMatcher.group(1);
            String[] importantInstructions = extractImportantNotices(noticeContent);
            for (String instruction : importantInstructions) {
                if (instruction != null && instruction.length() > 5) {
                    if (instructions.length() > 0) {
                        instructions.append("；");
                    }
                    instructions.append(instruction);
                }
            }
        }

        // 查找服用时间说明
        String[] timingPatterns = {
                "(饭前[服用]?)",
                "(饭后[服用]?)",
                "(空腹[服用]?)",
                "(餐时[服用]?)",
                "(睡前[服用]?)",
                "(晨起[服用]?)",
                "(开水冲服)",
                "(温水送服)"
        };

        for (String pattern : timingPatterns) {
            Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
            Matcher matcher = p.matcher(text);
            if (matcher.find()) {
                String timing = matcher.group(1);
                if (instructions.length() > 0) {
                    instructions.append("；");
                }
                instructions.append(timing);
                break; // 只取第一个匹配的服用方式
            }
        }

        String result = instructions.toString();

        // 控制长度，保留最重要的信息
        if (result.length() > 200) {
            String[] parts = result.split("；");
            StringBuilder shortResult = new StringBuilder();
            for (int i = 0; i < Math.min(parts.length, 4); i++) {
                if (shortResult.length() > 0) {
                    shortResult.append("；");
                }
                shortResult.append(parts[i].trim());
                if (shortResult.length() > 150) {
                    break;
                }
            }
            result = shortResult.toString();
        }

        if (!result.isEmpty()) {
            log.debug("提取到特殊说明信息: {}", result);
            return result;
        }

        log.debug("未能提取到特殊说明信息");
        return null;
    }

    /**
     * 从注意事项中提取重要信息
     */
    private String[] extractImportantNotices(String noticeContent) {
        List<String> importantNotices = new ArrayList<>();

        // 重要的注意事项关键词
        String[] importantKeywords = {
                "孕妇", "哺乳期", "儿童", "老年人", "过敏", "禁用", "慎用",
                "医师指导", "遵医嘱", "忌烟", "忌酒", "忌食"
        };

        // 分割注意事项条目
        String[] items = noticeContent.split("\\d+\\.");

        for (String item : items) {
            item = item.trim();
            if (item.length() < 5) continue;

            // 检查是否包含重要关键词
            for (String keyword : importantKeywords) {
                if (item.contains(keyword)) {
                    // 清理和简化内容
                    String cleanItem = cleanNoticeItem(item);
                    if (cleanItem.length() > 0 && cleanItem.length() <= 50) {
                        importantNotices.add(cleanItem);
                        break; // 找到一个关键词就够了
                    }
                }
            }

            // 最多提取4条重要注意事项
            if (importantNotices.size() >= 4) {
                break;
            }
        }

        return importantNotices.toArray(new String[0]);
    }

    /**
     * 清理注意事项条目
     */
    private String cleanNoticeItem(String item) {
        if (item == null) return "";

        return item
                .replaceAll("\\n+", " ") // 换行替换为空格
                .replaceAll("\\s+", " ") // 多个空格替换为单个
                .replaceAll("^[\\s\\d\\.]+", "") // 去掉开头的数字和点
                .replaceAll("应在医师指导下服用。?$", "需医师指导") // 简化常见表达
                .replaceAll("者禁用。?$", "禁用") // 简化禁用表达
                .replaceAll("者慎用。?$", "慎用") // 简化慎用表达
                .replaceAll("。+$", "") // 去掉结尾的句号
                .trim();
    }
}
